(function($){
    $(document).ready(function () {
        /*模板引擎设置*/
        _.templateSettings = {
            interpolate: /\{\{(.+?)\}\}/g
        };

        var InvoiceItemModel=Backbone.Model.extend({});

        var InvoiceItemCollection=Backbone.Collection.extend({
            model:InvoiceItemModel
        });


        var InvoiceItemView=Backbone.View.extend({
            tagName:"tr",
            render:function(){
                $(this.el).html(_.map([
                    this.model.get('quantity'),
                    this.model.get('description'),
                    this.model.get('price'),
                    this.model.calculateAmount()
                ],function(val,key){
                    return '<td>'+val+'</td>'
                }));

                return this;
            },

            initialize:function(){
                this.listenTo(this.model,'destroy',this.destroy,this);
            },

            destroy:function(){
                this.remove();
            }
        });

        var InvoiceItemListView=Backbone.View.extend({
            tagName:"table",
            className:"invoice-item-view",
            render:function(){
                $(this.el).empty();
                $(this.el).append($('<tr></tr>').html(_.map(['Quantity','Description','price','Total'],
                    function(val,key){
                        return '<th>'+val+'</th>';
                    }
                )));

                _.each(this.collection.models,function(model,key){
                    this.append(model);
                },this);

                return this;
            },

            append:function(model){
                $(this.el).append(new InvoiceItemListView({model:model}).render().el)
            },

            initialize:function(){
                this.listenTo(this.collection,'add',this.append,this);
            }

        });

        var invoiceItemModel=new InvoiceItemModel({
            description:"Farmer Figure",
            price:8,
            quantity:2
        });

        var invoiceItemView=new InvoiceItemView({
            model:invoiceItemModel
        });

        invoiceItemView.render();

        invoiceItemModel.set("quantity",12);

        window.invoiceItemModel=invoiceItemModel;



    });
})(jQuery);